#include<iostream>
#include"TcpServer.hpp"

using namespace TcpServerModule;
#include <functional>
#include <unordered_map>


#include "HttpProtocol.hpp"
using http_handler_t = std::function<void(HttpRequest&,HttpResponse&)>;

class HttpServer
{
    public:
    HttpServer(uint16_t port)
    :_tcpserver(std::make_unique<TcpServer>(port))
    {}
    void Resgiter(const std::string& type ,http_handler_t tmp)
    {
        _route[type]=tmp;
    }
    bool SafeCheck(std::string& service)
    {
        auto pos = _route.find(service);
        return pos != _route.end();
    }
    void Start()
    {
        _tcpserver->Init([this](SockPtr sockfd,InetAddr inetaddr){
            return this->HandlerQuest(sockfd,inetaddr);
        });
        _tcpserver->Loop();
    }
    bool HandlerQuest(SockPtr sockfd,InetAddr inetaddr)
    {
        LOG(LogLevel::DEBUG) << "HttpServer: get a new client: " << sockfd->Fd() << " addr info: " << inetaddr.Addr();
        std::string http_request;
        sockfd->Recv(&http_request);
        HttpRequest req;
      
        req.Deserialize(http_request);
        req.Print();
        HttpResponse resp;
        //请求被分为两类 第一类是 静态资源 第二类是动态资源
        if(req.IsHasArgs())//判断有没有参数
        {
            LOG(LogLevel::DEBUG)<<"访问请求有参数";
            std::string service = req.Path();
            if(SafeCheck(service))
            {
                 LOG(LogLevel::DEBUG)<<"路径无错"<<service;
                _route[service](req,resp);
            }
            else
            {
                LOG(LogLevel::DEBUG)<<"路径有错";
                resp.Build(req);
            }
        }
        else
        {
            LOG(LogLevel::DEBUG)<<"访问请求没有参数";
            resp.Build(req);
        }

        std::string resp_str;
        resp.Serialize(&resp_str);
        //LOG(LogLevel::DEBUG)<<resp_str;
        sockfd->Send(resp_str);
        // std::cout << http_request; //字节流的请求
        // // 读取请求，对请求进行分析处理 --> 文本处理！
        // // 1. 读取请求的完整性 --- 暂时不做
        // // 2. 完整http反序列化，http response序列化...
        // // demo 1 : 直接返回一个固定的内容
        //  std::string status_line = "HTTP/1.1 200 OK" + Sep + BlankLine;

        // // // 直接返回一个html网页
        // std::string body = "<!DOCTYPE html>\
        //                     <html>\
        //                    <head>\
        //                    <meta charset = \"UTF-8\">\
        //                    <title> Hello World</title>\
        //                    </head>\
        //                    <body>\
        //                    <p> Hello World</ p>\
        //                    </body> </html>";
        
        // std::string httpresponse = status_line + body;
        
        return true;
    }


    private:
    std::unique_ptr<TcpServer> _tcpserver; 
    std::unordered_map<std::string, http_handler_t> _route;;


};
